<template>
  <el-dialog
    title="训练日志"
    width="45%"
    v-model="state.TrainingLogShow"
    @close="DialogClosesCallback"
  >
    <el-scrollbar style="width: 100%; height: calc(100vh - 30rem)">
      <div id="messages"></div>
    </el-scrollbar>
  </el-dialog>
</template>

<script setup>
/**
 *
 */
import { reactive, ref, onMounted } from "vue";
/**
 * 存储
 */
import storageService from "@/utils/dataStore_utils";
/**
 *
 */
const state = reactive({
  TrainingLogShow: false,
});
/**
 *
 */
let eventSource;
/**
 * '
 */
const url = `http://192.168.1.121:5000/actuator/`;

/**
 * 生命周期
 */
onMounted(() => {
  /**
   *
   */
  console.log("----", storageService.sessionData.trainingName);
});

// 开启弹窗
const open = (row) => {
  state.TrainingLogShow = true;
  if (eventSource) {
    eventSource.close();
  }
  eventSource = new EventSource(url + storageService.sessionData.trainingName);
  /**
   *
   * @param event
   */
  eventSource.onmessage = function (event) {
    const messagesDiv = document.getElementById("messages");
    const newMessage = document.createElement("div");
    newMessage.textContent = `${event.data}`;
    messagesDiv.appendChild(newMessage);
  };
  eventSource.onerror = function () {
    const messagesDiv = document.getElementById("messages");
    const errorMessage = document.createElement("div");
    // 响应式的当前时间
    const currentTime = ref(new Date().toLocaleString());
    errorMessage.textContent =
      currentTime.value + "________错误：无法连接到SSE";
    messagesDiv.appendChild(errorMessage);
    console.log("----------", messagesDiv);
    eventSource.close();
  };
};

// 关闭弹窗
const close = () => {
  state.TrainingLogShow = false;
};

/**
 * Dialog 关闭的回调
 */
function DialogClosesCallback() {
  if (eventSource) {
    eventSource.close();
  }
}

defineExpose({ open, close });
</script>
